package com.yt.app.api.action.pay.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.google.common.base.Splitter;
import com.yt.app.api.util.Config;
import com.yt.core.MsgBean;
import com.yt.pay.AlipayConfig;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Description
 * <p>
 * </p>
 * DATE 2017/10/18.
 *
 * @author liujunshi.
 */
public class AlipayUtils {
    public static Map getPayParams(String orderNo, String body, String amount){
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest appPayRequest = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(body.toString());
        model.setSubject(body.toString());
        model.setOutTradeNo(orderNo);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(amount + "");
        model.setProductCode("QUICK_MSECURITY_PAY");
        appPayRequest.setBizModel(model);
        appPayRequest.setNotifyUrl(Config.apiUrl + AlipayConfig.NOTIFY_URL);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse payResponse = alipayClient.sdkExecute(appPayRequest);
            String orderString = payResponse.getBody();//就是orderString 可以直接给客户端请求，无需再做处理。
            Map<String, String> map = new HashMap<String, String>();
            map.put("orderString", orderString);
            /*orderString = URLDecoder.decode(orderString);
            Iterator<String> iterator = Splitter.on("&").split(orderString).iterator();
            while(iterator.hasNext()){
                String str = iterator.next();
                String[] kw = str.split("=");
                map.put(kw[0],kw[1]);
            }*/
            return map;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Map map =AlipayUtils.getPayParams("A00001232321", "体验商品信息", "0.01");
        MsgBean msgBean = new MsgBean();
        msgBean.put("parameterMap", map);
        System.out.println(JSONObject.toJSON(msgBean.returnMsg()).toString());
    }
}
